<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :needReturn="!flowFormType"
    >
      <template v-slot:full-button>
        <el-button
          :disabled="!canSave"
          v-if="
            !orderId &&
            $permission('assetStoreOrder:saveAndSubmit') &&
            !flowFormType
          "
          @click="saveAndSubmit()"
          >保存并提交</el-button
        >
        <el-button v-if="!flowFormType" :disabled="!canSave" @click="save()"
          >保存</el-button
        >
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-depotName>
              <el-input
                v-model="formInfo.data.depotName"
                class="not-mongolia"
                type="input"
                :required="true"
                :disabled="true"
                placeholder="请选择入库仓库"
              >
                <template #append>
                  <el-icon @click="selectStoreDepot"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-supplierName>
              <el-input
                type="input"
                :disabled="true"
                class="not-mongolia"
                placeholder="请选择供应商"
                v-model="formInfo.data.supplierName"
              >
                <!-- <template #append>
                  <el-icon @click="openSupplierWindow"><MoreFilled /></el-icon>
                </template> -->
              </el-input>
            </template>
          </page-form>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')" />
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <new-page-filter
            v-model:query="filterInfo.query"
            :filter-btn="filterInfo.list"
          >
            <template v-slot:filter-addEquipment>
              <el-button :disabled="!canEquipment" @click="addEquipment()"
                >添加资产
              </el-button>
            </template>
            <template v-slot:filter-removeEquipment>
              <el-button
                :disabled="!canRemoveEquipment"
                @click="removeEquipment()"
                >删除资产
              </el-button>
            </template>
            <template v-slot:filter-btn>
              <el-button @click="changeNumberAll(true)">一键填充</el-button>
              <el-button @click="changeNumberAll(false)">一键清空</el-button>
            </template>
            <template v-slot:filter-brand>
              <el-button :disabled="!canSave" @click="allSetBrand()"
                >一键设置厂家
              </el-button>
            </template>
          </new-page-filter>
          <div class="flex_full_item">
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :tab-index="true"
                row-key="rowId"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-qty="scope">
                  <el-form-item
                    v-if="scope.row.qtyOperateMode !== 3"
                    class="margin-bottom"
                  >
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.largeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              v-model.lazy="scope.row.largeUnitQty"
                              style="width: 100%; margintop: 18px"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              :min="0"
                              :max="largeMax(scope.row)"
                              @change="
                                changeLarge(
                                  $event,
                                  scope.row,
                                  `data.${scope.$index}.largeUnitQty`
                                )
                              "
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            <!--{{ scope.row.unitName }}-->
                          </div>
                        </div>
                        <div
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                          class="page-table-input-number-item"
                        >
                          <el-form-item>
                            <el-input-number
                              v-model.lazy="scope.row.smallUnitQty"
                              style="width: 100%; margintop: 18px"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="smallMax(scope.row)"
                              @change="changeSmall($event, scope.row)"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            <!--{{ scope.row.calcUnitName }}-->
                          </div>
                        </div>
                      </div>
                      <div
                        v-if="scope.row.qtyOperateMode === 2"
                        class="page-table-input-number-right"
                      >
                        {{ $fn.qtyFormatter(scope.row.qty) }}
                      </div>
                    </div>
                  </el-form-item>
                  <span v-else>{{ $fn.qtyFormatter(scope.row.qty) }}</span>
                </template>
                <template v-slot:col-installCost="scope">
                  <el-form-item
                    v-if="scope.$index >= 0"
                    :prop="`data.${scope.$index}.installCost`"
                    :rules="
                      scope.$index >= 0
                        ? [
                            {
                              validator: $validate.positiveMoneyZeroAsset,
                              trigger: 'blur',
                            },
                          ]
                        : []
                    "
                  >
                    <el-input-number
                      v-model.lazy="scope.row.installCost"
                      style="width: 100%"
                      clearable
                      controls-position="right"
                      :precision="systemConfig.assets_price_precision"
                      :min="0"
                      :max="99999999"
                    />
                  </el-form-item>
                </template>
                <template v-slot:col-transportCost="scope">
                  <el-form-item
                    v-if="scope.$index >= 0"
                    :prop="`data.${scope.$index}.transportCost`"
                    :rules="
                      scope.$index >= 0
                        ? [
                            {
                              validator: $validate.positiveMoneyZeroAsset,
                              trigger: 'blur',
                            },
                          ]
                        : []
                    "
                  >
                    <el-input-number
                      v-model.lazy="scope.row.transportCost"
                      style="width: 100%"
                      clearable
                      controls-position="right"
                      :precision="systemConfig.assets_price_precision"
                      :min="0"
                      :max="99999999"
                    />
                  </el-form-item>
                </template>
                <template v-slot:col-taxCost="scope">
                  <el-form-item
                    v-if="scope.$index >= 0"
                    :prop="`data.${scope.$index}.taxCost`"
                    :rules="
                      scope.$index >= 0
                        ? [
                            {
                              validator: $validate.positiveMoneyZeroAsset,
                              trigger: 'blur',
                            },
                          ]
                        : []
                    "
                  >
                    <el-input-number
                      v-model.lazy="scope.row.taxCost"
                      style="width: 100%"
                      clearable
                      controls-position="right"
                      :precision="systemConfig.assets_price_precision"
                      :min="0"
                      :max="99999999"
                    />
                  </el-form-item>
                </template>
                <template v-slot:col-brandName="scope">
                  <el-form-item
                    v-if="scope.$index >= 0"
                    :prop="`data.${scope.$index}.brandName`"
                  >
                    <el-input
                      type="input"
                      :disabled="true"
                      class="not-mongolia"
                      placeholder="请选择厂家"
                      v-model="scope.row.brandName"
                    >
                      <template #append>
                        <el-icon @click="selectBrand(scope.$index)"
                          ><MoreFilled
                        /></el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <!--选择仓库-->
    <SelectDepot
      v-if="selectDepotInfo.visible"
      v-model:show-dialog="selectDepotInfo.visible"
      :check-box="false"
      :query="selectDepotInfo.query"
      :highlight-row="true"
      :check-lock="true"
      :save-empty="true"
      @callback="selectDepotCallBack"
    />
    <!--选择设备-->
    <SelectEquipmentArchives
      v-if="equipmentInfo.visible"
      v-model:visible="equipmentInfo.visible"
      :queryParams="equipmentInfo.query.queryParams"
      :query="equipmentInfo.query.queryMap"
      :api="getStoreDetailByReceive"
      @callback="equipmentBack"
    />
    <!-- 添加厂家 -->
    <SelectBrand
      v-if="selectBrandInfo.visible"
      v-model:showDialog="selectBrandInfo.visible"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectBrandCallBack"
    />
    <select-supplier
      v-if="selectProductSupplier.visible"
      v-model:show-dialog="selectProductSupplier.visible"
      :query="selectProductSupplier.query"
      :check-box="false"
      :saveEmpty="true"
      :highlight-row="true"
      :api="selectProductSupplier.api"
      @callback="selectSupplierCallback"
    />
    <CapitalSourceAdjustAssetStore
      v-if="capitalSourceAdjustInfo.visible"
      v-model:show-dialog="capitalSourceAdjustInfo.visible"
      :right-data="capitalSourceAdjustInfo.rightData"
      @callback="capitalSourceAdjustCallback"
    />
  </div>
</template>

<script setup name="AssetStoreOrderModifyReceive">
import { getSupplierPage } from '@/api/core'
const CapitalSourceAdjustAssetStore = defineAsyncComponent(() =>
  import('../../components/capitalSourceAdjustAssetStore')
)
const SelectEquipmentArchives = defineAsyncComponent(() =>
  import('./selectAsset')
)
import {
  getStoreDetailByReceive,
  createAssetStoreOrder,
  createAssetStoreOrderAndSave,
  submitAssetStoreOrder,
  detailAssetStoreOrder,
  getAssetStoreOrderDetailAll,
  getAssetStoreOrderDetailCustomizeList,
  getDeviceReceiveStoreOrderDetailAll,
  updateAssetStoreOrder,
} from '@/api/asset'
import { getCustomizeSetting } from '@/api/customize'

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps([
  'visible',
  'title',
  'receiveOrder',
  'orderId',
  'id',
  'flowFormType',
])

const productionTimePickerOptions = ref({
  disabledDate(time) {
    return time.getTime() > Date.now() - 8.64e6
  },
})
const validityTimePickerOptions = ref({
  disabledDate(time) {
    return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
  },
})
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
//用于存储收货单数据
const receiveData = ref([])
const supplierId = ref(undefined)
const supplierName = ref(undefined)
//更新数据
const updateData = ref([])
//用于限定设备只能查询那些ID
const receiveEqupmentQueryIds = ref([])
//表单相关
const formInfo = ref({
  ref: null,
  data: {
    depotName: '',
    depotId: '',
    deptName: '',
    deptId: '',
    supplierId: props.receiveOrder.supplierId || '',
    supplierName: props.receiveOrder.supplierName || '',
    receiveNo: props.receiveOrder.orderNo || '',
    receiveId: props.receiveOrder.id || '',
  },
  fieldList: [
    {
      label: '入库单号',
      value: 'orderNo',
      type: 'input',
      disabled: true,
    },
    {
      label: '入库仓库',
      value: 'depotName',
      type: 'slot',
      require: true,
    },
    {
      label: '供应商',
      value: 'supplierName',
      type: 'slot',
      required: false,
    },
    /* {
      label: '入库部门',
      value: 'deptName',
      type: 'input',
      disabled: true,
    }, */
    {
      label: '入库类型',
      value: 'increaseType',
      type: 'select-model',
      code: 'increase_type',
      required: true,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 200,
    },
  ],
  rules: {
    depotName: [
      { required: true, message: '请选择入库仓库', trigger: 'change' },
    ],
    supplierName: [
      { required: true, message: '请选择供应商', trigger: 'change' },
    ],
    phone: [{ validator: proxy.$validate.cellphone, trigger: 'blur' }],
    increaseType: [
      {
        required: true,
        message: '请选择入库方式',
        trigger: 'blur',
      },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id || props.orderId,
      },
    },
    queryParams: {
      receiveAll: true,
      // contractId: "",
      pendReceiveGtZero: true,
      receiveId: '',
    },
  },
  list: [
    { type: 'slot', value: 'addEquipment' },
    { type: 'slot', value: 'removeEquipment' },
    { type: 'slot', value: 'btn' },
    { type: 'slot', value: 'brand' },
  ],
})
const capitalSourceAdjustInfo = ref({
  visible: false,
  row: {},
  leftData: [],
  rightData: [],
})
const selectBrandInfo = ref({
  visible: false,
  index: 0,
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '资金来源',
        event: adjustAmount,
        show: true,
      },
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: removeProduct,
        show: true,
      },
    ],
  },
})
const selectDepotInfo = ref({
  visible: false,
  query: {
    depotAuth: 'id',
    status: 1,
    deptId: '',
    useTypeId: 2,
  },
})
const equipmentInfo = ref({
  visible: false,
  query: {
    queryMap: {
      id: { queryType: 'NOT_IN', queryCategory: 'AND', value: null },
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      supplierId: {
        queryType: 'ALL_LIKE',
        value: '',
      },
    },
    queryParams: {
      receiveAll: true,
      // contractId: "",
      pendReceiveGtZero: true,
      receiveId: '',
    },
  },
})
const selectProductSupplier = ref({
  visible: false,
  api: getSupplierPage,
  query: {
    supplierAuth: 'supplierId',
  },
})
const btnLoading = ref(true)
const formRefs = ref([])

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canRemoveEquipment = computed(() => {
  return tableInfo.value.selections.length
})
const canEquipment = computed(() => {
  return (
    formInfo.value.data.depotId &&
    formInfo.value.data.deptId &&
    formInfo.value.data.supplierId
  )
})
const canImport = computed(() => {
  return formInfo.value.data.depotId && formInfo.value.data.deptId
})

watch(
  () => tableInfo.value.data,
  () => {
    tableInfo.value.data.forEach((row) => {
      let smallUnitQty = parseFloat(row.smallUnitQty || 0)
      let unitConvertCoefficient = 1
      let largeUnitQty = parseFloat(row.largeUnitQty || 0)
      let calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
        smallUnitQty
      )
      let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
      row['calcQty'] = calcQty
      row['qty'] = qty
      row.sumAmount = proxy.$fn.accDiv(
        proxy.$fn.accMul(row.calcQty, parseFloat(row.price)),
        unitConvertCoefficient
      )
    })
  },
  {
    deep: true,
  }
)

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  })
})
function adjustAmount(row) {
  if (row.capitalSourceList) {
    capitalSourceAdjustInfo.value.rightData = row.capitalSourceList
  } else {
    const sumAmount =
      row.sumAmount + row.installCost + row.transportCost + row.taxCost
    capitalSourceAdjustInfo.value.rightData = [
      {
        code: '1',
        amount: sumAmount,
      },
    ]
  }
  // capitalSourceAdjustInfo.value.rightData = row.capitalSourceList || []
  capitalSourceAdjustInfo.value.visible = true
  capitalSourceAdjustInfo.value.row = row
}
function removeProduct(selectRow = undefined) {
  if (selectRow) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function capitalSourceAdjustCallback(data) {
  let row = capitalSourceAdjustInfo.value.row
  row.capitalSourceList = data
}
function selectSupplierCallback(row) {
  if (row.supplierId !== formInfo.value.data.supplierId) {
    tableInfo.value.data = []
  }
  if (row) {
    formInfo.value.data.supplierId = row.supplierId
    formInfo.value.data.supplierName = row.supplierName
    equipmentInfo.value.query.queryMap.supplierId.value = row.supplierId
  } else {
    formInfo.value.data.supplierId = ''
    formInfo.value.data.supplierName = ''
    equipmentInfo.value.query.queryMap.supplierId.value = ''
  }
}
setData()
function setData() {
  let obj = {
    orderNo: {
      label: '单号',
      value: 'orderNo',
      componentType: 'input',
      show: false,
      hidden: true,
    },
    qty: {
      label: '数量',
      value: 'qty',
      type: 'slot',
      minWidth: '250px',
      hidden: true,
    },
    supplierName: {
      label: '供应商',
      value: 'supplierName',
      type: 'column',
      hidden: true,
    },
    preQty: {
      label: '可入库数量',
      value: 'preQty',
      type: 'column',
      componentType: 'column',
      formatter: proxy.$fn.qtyFixedFormatter,
      show: false,
      hidden: true,
    },
    receiveQty: {
      label: '收货数量',
      value: 'receiveQty',
      type: 'column',
      componentType: 'column',
      formatter: proxy.$fn.qtyFixedFormatter,
      show: false,
      hidden: true,
    },
    price: {
      label: '单价',
      value: 'price',
      minWidth: '150px',
      type: 'column',
      rules: {
        validator: proxy.$validate.positiveMoney,
        trigger: 'blur',
      },
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('assetStoreOrder:price'),
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('assetStoreOrder:price'),
      hidden: true,
    },
    forceAcceptValue: {
      label: '是否强制验收',
      value: 'forceAcceptValue',
      type: 'slot',
      hidden: true,
    },
    installCost: {
      label: '安装费',
      value: 'installCost',
      minWidth: '150px',
      type: 'slot',
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
    transportCost: {
      label: '运杂费',
      value: 'transportCost',
      minWidth: '150px',
      type: 'slot',
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
    taxCost: {
      label: '税费',
      value: 'taxCost',
      minWidth: '150px',
      type: 'slot',
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
    brandName: {
      label: '厂家名称',
      value: 'brandName',
      minWidth: '250px',
      type: 'slot',
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
  if (props.receiveOrder.id) {
    formInfo.value.fieldList = formInfo.value.fieldList.filter(
      (item) => item.value !== 'orderNo'
    )
  }
}
//数量操作模式 qtyOperateMode：0整数模式，2自动算出小数，1手动输入小数
function largeMax(row) {
  //原厂码最大为1[0,1]
  if (row.qtyOperateMode === 2) {
    return parseInt(row.preCalcQty / row.unitConvertCoefficient)
  } else {
    return row.preQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(row.preCalcQty / row.unitConvertCoefficient)
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.preCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  if ((row.qtyOperateMode === 2 && row.stockQty > 0) || row.codeType === 3) {
    if (e === 1) {
      row.smallUnitQty = 0
    }
  }
  proxy.$nextTick(() => {
    proxy.$refs.tableForm.clearValidate(str)
  })
}
function changeSmall(e, row) {
  if (row.qtyOperateMode === 2) {
    if ((row.codeType === 2 && row.stockQty > 0) || row.codeType === 3) {
      if (e > 0) {
        row.largeUnitQty = 0
      }
    }
  }
}
function changeNumberAll(type) {
  tableInfo.value.data.forEach((item) => {
    if (type) {
      item.largeUnitQty = item.preQty
      item.qty = item.preQty
      item.calcQty = item.preCalcQty
    } else {
      item.largeUnitQty = 0
      item.qty = 0
    }
  })
}
function allSetBrand(selectRow = undefined) {
  selectBrandInfo.value.visible = true
  selectBrandInfo.value.index = -2
}
function selectBrand(index) {
  selectBrandInfo.value.index = index
  selectBrandInfo.value.visible = true
}
function selectBrandCallBack(row) {
  const index = selectBrandInfo.value.index
  if (row) {
    if (index === -2) {
      tableInfo.value.data.forEach((item) => {
        item.brandId = row.id
        item.brandName = row.name
      })
      return
    }
    tableInfo.value.data[index].brandId = row.id
    tableInfo.value.data[index].brandName = row.name
  } else {
    tableInfo.value.data[index].brandId = '-2'
    tableInfo.value.data[index].brandName = ''
  }
}

function openSupplierWindow() {
  selectProductSupplier.value.visible = true
}
function getList() {
  if (
    (props.id || props.orderId) &&
    props.receiveOrder.id &&
    props.receiveOrder.id !== -2
  ) {
    tableInfo.value.data = []
    getAssetStoreOrderDetailCustomizeList(filterInfo.value.query).then(
      (res) => {
        if (res && res.success) {
          res.data.forEach((item) => {
            item.rowId = proxy.$fn.getUid()
            supplierId.value = item.supplierId
            supplierName.value = item.supplierName
            item.installCost = item.installCost || 0
            item.transportCost = item.transportCost || 0
            item.taxCost = item.taxCost || 0
          })
          tableInfo.value.data = res.data
          receiveData.value = proxy.$fn.deepClone(tableInfo.value.data)
        }
      }
    )
  } else {
    tableInfo.value.data = []
    const templateRow = props.receiveOrder
    formInfo.value.data.receiveId = props.receiveOrder.id
    supplierId.value = props.receiveOrder.supplierId
    supplierName.value = props.receiveOrder.supplierName
    getStoreDetailByReceive(filterInfo.value.query).then((res) => {
      if (res && res.success) {
        let rows = res.data.mergeDetails || []
        rows = rows.map((row) => {
          row.installCost = row.installCost || 0
          row.transportCost = row.transportCost || 0
          row.taxCost = row.taxCost || 0
          return {
            ...row,
            price: row.price || 0,
            largeUnitQty: 0,
            preQty: row.preQty,
            qty: row.qty,
            supplierId: templateRow.supplierId,
            supplierName: templateRow.supplierName,
            deviceType: row.deviceType,
            deviceTypeValue: row.deviceTypeValue,
            rowId: proxy.$fn.getUid(),
          }
        })
        receiveData.value = rows
        tableInfo.value.data = rows
      }
    })
  }
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
    case 'changePrice':
      proxy.$refs.tableForm.clearValidate(data)
      break
  }
}
// 外部流程组件也需调用
function saveAndSubmit(flowData) {
  save(true, flowData)
}
function save(isSaveAndSubmit, obj = {}) {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let notQtyDetails = tableInfo.value.data
      .filter((row) => !row.qty)
      .map((item) => item.productCode)
    if (notQtyDetails.length) {
      proxy.$message({
        message: `请填写产品编码为【${notQtyDetails}】的数量`,
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    let data = formInfo.value.data
    data.mergeDetails = tableInfo.value.data
    let res = checkoutPriceTotal(tableInfo.value.data)
    if (!res) {
      return
    }
    let api = data.id
      ? updateAssetStoreOrder
      : isSaveAndSubmit === true
      ? createAssetStoreOrderAndSave
      : createAssetStoreOrder
    // 如果是保存并提交
    if (isSaveAndSubmit) {
      if (proxy.$route.query.processInstanceId) {
        api = submitAssetStoreOrder
      }
      data = {
        orderData: data,
        // flowTaskCommentDto和processDefinitionKey为审批流程需要传递的参数
        flowTaskCommentDto: { approvalType: 'submit' },
        processDefinitionKey: 'assetStore',
        processInstanceId: obj.processInstanceId,
        taskId: obj.taskId,
      }
    }
    api(data).then((resp) => {
      if (resp && resp.success) {
        if (proxy.$route.query.processInstanceId) {
          proxy.$router.push(proxy.$route.query.backRouter)
          return
        }
        showDialog.value = false
        emits('returnModify')
      }
    })
  })
}
function checkoutPriceTotal(data) {
  for (let index = 0; index < data.length; index++) {
    const element = data[index]
    // if (
    //   !element.hasOwnProperty('capitalSourceList') ||
    //   (element.hasOwnProperty('capitalSourceList') &&
    //     !element.capitalSourceList.length)
    // ) {
    //   proxy.$message({
    //     message: `编码为【${element.productCode}】的资产字典资金来源不能为空！`,
    //     type: 'warning',
    //     duration: 3500,
    //     showClose: true,
    //   })
    //   return false
    // }
    let rowTotal = 0
    let sumAmount = element.sumAmount
    let installCost = element.installCost
    let transportCost = element.transportCost
    let taxCost = element.taxCost
    rowTotal = proxy.$fn.accAdd(sumAmount || 0, installCost || 0)
    rowTotal = proxy.$fn.accAdd(rowTotal || 0, transportCost || 0)
    rowTotal = proxy.$fn.accAdd(rowTotal || 0, taxCost || 0)
    if (
      !element.hasOwnProperty('capitalSourceList') ||
      (element.hasOwnProperty('capitalSourceList') &&
        !element.capitalSourceList.length)
    ) {
      element.capitalSourceList = [
        {
          code: '1',
          amount: rowTotal,
        },
      ]
    }
    let capitalSourceList = element.capitalSourceList
    let capitalSourceListTotal = 0
    if (capitalSourceList && capitalSourceList.length) {
      capitalSourceList.forEach((item) => {
        capitalSourceListTotal = proxy.$fn.accAdd(
          capitalSourceListTotal || 0,
          item.amount || 0
        )
      })
    }
    element._isEqualPrice = rowTotal == capitalSourceListTotal
    if (!element._isEqualPrice) {
      proxy.$message({
        message: `编码为【${element.productCode}】的资产字典，总金额+安装费+运杂费+税费为【${rowTotal}】，不等于资金来源总费用【${capitalSourceListTotal}】`,
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return false
    }
  }
  return true
}
//选择入库仓库
function selectStoreDepot() {
  selectDepotInfo.value.visible = true
}
function selectDepotCallBack(data = undefined) {
  formInfo.value.data.depotId = data.id
  formInfo.value.data.depotName = data.name
  formInfo.value.data.deptName = data.deptName || ''
  formInfo.value.data.deptId = data.deptId || ''
  tableInfo.value.map = new Map()
}
//选择产品
function addEquipment() {
  equipmentInfo.value.query.queryMap.orderId.value = props.receiveOrder.id
  equipmentInfo.value.query.queryParams.receiveId = props.receiveOrder.id
  equipmentInfo.value.query.queryMap.id.value = tableInfo.value.data
    .map((item) => item.id)
    .toString()
  if (props.id || props.orderId) {
    equipmentInfo.value.query.queryParams.storeId = props.id || props.orderId
    equipmentInfo.value.query.queryMap.id.value = tableInfo.value.data
      .map((item) => item.receiveDetailId)
      .toString()
  }
  equipmentInfo.value.visible = true
}
function equipmentBack(data) {
  data.forEach((item) => {
    item.supplierId = supplierId.value
    item.supplierName = supplierName.value
    item.installCost = 0
    item.transportCost = 0
    item.taxCost = 0
    if (receiveData.value && receiveData.value.length > 0) {
      receiveData.value.forEach((receive) => {
        if (item.id == receive.productId) {
          item.price = receive.price
          item.receiveQty = receive.receiveQty
          item.preQty = receive.preQty
          item.productId = receive.productId
          item.receiveDetailId = receive.receiveDetailId
          receiveEqupmentQueryIds.value.splice(
            receiveEqupmentQueryIds.value.indexOf(item.id),
            1
          )
        }
      })
    }
  })
  //设备返回
  tableInfo.value.data = data.concat(tableInfo.value.data)
  tableInfo.value.data.forEach((item) => {
    item.isChoice = false
  })
  tableInfo.value.list = tableInfo.value.data.slice(0, 50)
}
//删除产品
function removeEquipment(selectRow = undefined) {
  if (selectRow && selectRow.productId) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.selections.map((item) => {
          receiveEqupmentQueryIds.value.push(item.productId)
        })
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice && row.codeType === 3) {
    return 'success-row'
  } else {
    return ''
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'assetStoreOrderModify-com.slip.spd.entity.vo.device.store.AssetStoreOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      filterInfo.value.query.customizeUserVO = data
      if (props.receiveOrder.id) {
        filterInfo.value.query.queryMap.orderId.value = props.receiveOrder.id
        filterInfo.value.query.queryParams.receiveId = props.receiveOrder.id
      }
      if (props.id || props.orderId) {
        filterInfo.value.query.queryMap.orderId.value =
          props.id || props.orderId
      }
      if (props.id || props.orderId) {
        getMain()
      }
      getList()
    }
  })
}
function getMain() {
  detailAssetStoreOrder(props.id || props.orderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
      filterInfo.value.query.queryMap.receiveId.value = props.receiveId
      getList()
    }
  })
}
// 名称不要做改变，在流程引擎中需要通过refs进行调用
defineExpose({
  save,
  saveAndSubmit,
})
</script>

<style scoped></style>
